import { Component } from '@angular/core';
import {
  IonicPage,
  NavController,
  ToastController,
  NavParams,
  AlertController,
  LoadingController,
  App
} from 'ionic-angular';
import { ProjectPlanApi } from '../../api/project/ProjectPlanApi';
import { LoginApi } from '../../api/login/LoginApi';
import { OfflineDataApi } from '../../api/offline-data/OfflineDataApi';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'project-plan.html'
})
export class ProjectPlan {
  myAppDatabase: SQLiteObject;

  private position: string;
  private projectPlans: [object];
  private username: string;
  private fresh: any;

  //  页面即将进入时调用
  ionViewWillEnter() {
    this.getData();
  }

  constructor(private sqlite: SQLite, public offlineDataApi: OfflineDataApi, public loginApi: LoginApi, private app: App, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private planApi: ProjectPlanApi, public params: NavParams, public navCtrl: NavController, private toastCtrl: ToastController) {
    this.position = params.get("position");
    this.username = params.get("userName");
    this.planApi.getMyProjectPlanInfos(this.position).subscribe(res => {
      let result = JSON.parse(res);
      if (result.state) {
        this.projectPlans = result.data;
      }
    });
  }

  getData() {
    this.sqlite.create({
      name: 'ionicdb.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      db.executeSql('CREATE TABLE IF NOT EXISTS materiel(rowid INTEGER PRIMARY KEY ,date TEXT,companyId VARCHAR,name TEXT,code TEXT,qrcode TEXT,length decimal(50,2), width decimal(50,2), height decimal(50,2),emptyWeight decimal(50,3),volume decimal(50,3),takePhoto INT,materielId VARCHAR,pklmaterielId VARCHAR)', [])
        .then(res => console.log('初始化表 materiel'))
        .catch(e => console.log(e.message)); 
      db.executeSql('CREATE TABLE IF NOT EXISTS container(rowid INTEGER PRIMARY KEY ,date TEXT,companyId ,id VARCHAR,name TEXT,code TEXT, qrcode TEXT,length decimal(50,3), width decimal(50,2), height decimal(50,2),deadWeight decimal(50,3),bearWeight decimal(50,3),containerType INT)', [])
        .then(res => console.log('初始化表 container'))
        .catch(e => console.log(e.message));
      this.myAppDatabase = db;
    }).catch(e =>
      this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message)
    );
  }

  goException(event) {
    this.navCtrl.push("ExceptionReport", {
      "planId": event.target.parentElement.name,
      "planPositionId": event.target.parentElement.lang
    });
  }

  actionIn(event) {
    this.navCtrl.push("LoadContainer", {
      "projectId": event.target.parentElement.title,
      "planId": event.target.parentElement.name,
      "planPositionId": event.target.parentElement.lang
    });
  }

  actionOut(event) {
    this.navCtrl.push("UnloadContainer", {
      "projectId": event.target.parentElement.title,
      "planId": event.target.parentElement.name,
      "planPositionId": event.target.parentElement.lang,
    });
  }

  rule() {
    //点击检验货物,跳转到货物检验扫描界面
    this.navCtrl.push("RuleScan", { "positionId": this.position });
  }

  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }

  logOut() {
    let alert = this.alertCtrl.create({
      title: '你确定要退出当前用户吗？',
      message: "点击确定将退出到登录页面!",
      buttons: ['取消',
        {
          text: '确定',
          handler: data => {
            //点击确定,跳转到登录页面

            const http$ = this.loginApi.out(this.username);
            http$.subscribe((val: any) => {
              let res = JSON.parse(val);
              if (res.state) {
                this.app.getRootNav().push('LoginPage', { "backButtontag": true });//用this.app.getRootNav() 从根页面跳转
                localStorage.removeItem("token");
                localStorage.removeItem("userInfo");
              } else {
                this.showMsg("系统出错,请重试!");
              }
            });
            /*//清除可能出现的返回键BUG
            setTimeout(() => {
              this.navCtrl.popAll();
            },1000);*/
          }
        }]
    });
    alert.present();
  }

  refreshCache() {
    let now = new Date();
    let loading = this.loadingCtrl.create({
      content: '下载中,请耐心等待...'
    });
    loading.present();
    this.offlineDataApi.refreshCache().subscribe(res => {
      if (res.state) {
        let success = true;
        this.myAppDatabase.transaction(tx => {
          tx.executeSql('DELETE FROM materiel WHERE companyId=?',
            [res.companyId]
            , () => {
              //  console.log('删除materiel ');
            }
            , e => {
              //  console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
              success = false;
            }
          );
          tx.executeSql('DELETE FROM container WHERE companyId=?',
            [res.companyId]
            , () => {
              //  console.log('container ');
            }
            , e => {
              //  console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
              success = false;
            }
          );
          let materiels: [any] = res.materiels;
          if (materiels != null || materiels.length > 0) {
            for (var materiel of materiels) {
              tx.executeSql('INSERT INTO materiel VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                [this.myFormat('yyyy-MM-dd hh:mm:ss', now), materiel.companyId, materiel.materielName, materiel.materielCode, materiel.materielQrcode, materiel.length, materiel.width, materiel.height, materiel.emptyWeight, materiel.volume, materiel.takePhoto,materiel.materielId,materiel.id]
                , () => {
                  //  console.log('insert into materiel table successfully');
                }
                , e => {
                  //  console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
                  success = false;
                }
              );
            }
          }
          let containers: [any] = res.containers;
          if (containers != null || containers.length > 0) {
            for (var container of containers) {
              tx.executeSql('INSERT INTO container VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?)',
                [this.myFormat('yyyy-MM-dd hh:mm:ss', now), container.companyId, container.id,container.containerName, container.containerCode, container.qrcode, container.longs, container.wide, container.high,container.deadWeight, container.bearWeight,container.containerType]
                , () => {
                  // console.log('insert into container table successfully');
                }
                , e => {
                  // console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
                  success = false;
                }
              );
            }
          }
        })
        .then(res => console.log('更新缓存结束'))
        .catch(e => console.log(e));
        loading.dismiss();
        if (success) {
          this.showMsg("更新成功!");
        } else {
          this.showMsg("更新失败!请保证网络通畅的情况再试！");
        }
      } else {
        loading.dismiss();
        this.showMsg(res.msg);
      }
    });
  }

  doRefresh(refresher) {
    this.planApi.getMyProjectPlanInfos(this.position).subscribe(res => {
      let result = JSON.parse(res);
      if (result.state) {
        this.fresh = result.data;
      }
    });

    setTimeout(() => {
      this.projectPlans = this.fresh;
      refresher.complete();
    }, 1200);
  }

  myFormat(fmt: string, data: Date) {
    var o = {
      "M+": data.getMonth() + 1,                 //月份
      "d+": data.getDate(),                    //日
      "h+": data.getHours(),                   //小时
      "m+": data.getMinutes(),                 //分
      "s+": data.getSeconds(),                 //秒
      "q+": Math.floor((data.getMonth() + 3) / 3), //季度
      "S": data.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (data.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }


}
